import json
import urllib

import requests
from myspider.user_agent import getheaders
from requests.cookies import RequestsCookieJar


class MoSpider(object):
    def __init__(self):
        self.sess = requests.Session()
        self.headers = {
            "accept": "*/*",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "zh-CN,zh;q=0.9",
            "cookie": "__mgjuuid=2bb1dc2f-223b-4322-a64f-93d7b23fcec1",
            "referer": "https://shop.mogu.com/detail/1lsuvke?acm=3.mce.1_10_1l1a0.133798.0.1xwTLrJ8bqFhG.pos_2-m_490688-sd_119",
            "sec-fetch-mode": "no-cors",
            "sec-fetch-site": "same-site",
            "user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
        }

    def Test_spider(self):
        url = self.get_url()
        html1 = self.sess.get(
            'https://list.mogu.com/module/mget?code=sketch&callback=httpCb157508719634374&_=1575087196344',
            headers=self.headers)
        cookies = html1.cookies
        print(cookies)
        self.headers[
            "referer"] = "https://shop.mogu.com/detail/1lsuvke?acm=3.mce.1_10_1l1a0.133798.0.1xwTLrJ8bqFhG.pos_2-m_490688-sd_119"
        html = self.sess.get(url, headers=self.headers,cookies=cookies)
        print(html.text)
        print(html.cookies)

    def get_url(self):
        dic_data = {"page": 1, "pageSize": 24, "sort": "pop", "ratio": "3:4", "cKey": "pc-search-wall",
                    "q": "%E8%A1%AC%E8%A1%A3", "from": "querytip0", "ptp": "31.v5mL0b.0.0.auWtOczJ"}
        json_data = json.dumps(dic_data)
        formdata = {
            'data': json_data,
            "mw-ckey": "pc-search-wall",
            "mw-appkey": "100028",
            "mw-ttid": "NMMain@mgj_pc_1.0",
            "mw-t": "1575039016530",
            "mw-uuid": "185edc4a-dcf1-47bb-b2cf-8a0f9aebfa15",
            "mw-h5-os": "unknown",
            "mw-sign": "22ca33752c2e5b53e5b5954446575bd3",
            "callback": "mwpCb2",
            "_": "1575039016531",
        }
        url = 'https://api.mogu.com/h5/mwp.pagani.search/19/?'
        json_dd = json.dumps(formdata)
        quote_params = urllib.parse.urlencode(formdata)
        params = quote_params.replace('+', '')
        url = url + params
        return url


if __name__ == '__main__':
    ms = MoSpider()
    ms.Test_spider()
